/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package s.f.login;

import s.f.usuarios.CRUD_Usuarios;
import s.f.util.AppException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Froy
 */
public class FiltroLoginAdmin1 implements Filter {

    //private ServletContext context;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //context = filterConfig.getServletContext();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession sesion = req.getSession(true);

        boolean valLogin = false;
        if (request.getParameter("BTNLOGIN") != null) {
            if (request.getParameter("BTNLOGIN").equals("Acceder")) {

                String usr = request.getParameter("TXTUSER");
                String pass = request.getParameter("TXTCONTRASENA");
                                
                try {
                    valLogin = CRUD_Usuarios.compareUser(usr, pass);
                } catch (SQLException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                } catch (AppException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (valLogin) {
                    sesion.setAttribute("usuario", request.getParameter("TXTUSER"));
                    chain.doFilter(request, response);
                } else {
                    HttpServletResponse resp = (HttpServletResponse) response;
                    resp.sendRedirect("/empleados/login.jsp");
                }
            }
        }
    }

    @Override
    public void destroy() {
    }
}
